 /*
  * Copyright (c) 2021, 2023, yishun.cn All rights reserved.
  *
  */
 package cn.shun.aop;

 import cn.hutool.core.lang.Dict;
 import cn.shun.dto.PageInfoDto;
 import cn.shun.local.PageInfoThreadLocal;
 import cn.shun.pojo.User;
 import com.github.pagehelper.Page;
 import com.github.pagehelper.PageHelper;
 import com.github.pagehelper.PageInfo;
 import jakarta.servlet.http.HttpServletRequest;
 import lombok.extern.slf4j.Slf4j;
 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.annotation.*;
 import org.springframework.stereotype.Component;
 import org.springframework.web.context.request.RequestContextHolder;
 import org.springframework.web.context.request.ServletRequestAttributes;

 import java.lang.reflect.Array;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;

 /**
  * <p>Project: sboot_2023-cn.shun.aop-PageAop
  * <p>Powered by yishun On 2023-04-14 16:27:43
  *
  * @author yishun [2465734101@qq.com]
  * @version 1.0
  * @since 17
  */
 @Component
 @Aspect
 @Slf4j
 public class PageAop {
     /**
      * 切入点
      */
     @Pointcut("@annotation(cn.shun.annotation.PageX)")
     public void point() {

     }

     @Around("point()")
     public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
         ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
         HttpServletRequest request = requestAttributes.getRequest();
         String pageNum = request.getParameter("pageNum");
         String pageSize = request.getParameter("pageSize");
         if (pageNum != null && pageSize != null) {
             int pn = Integer.parseInt(pageNum);
             int ps = Integer.parseInt(pageSize);
             PageHelper.startPage(pn, ps);
         }


         Object value = joinPoint.proceed();
         if (value instanceof Page) {
             Page page = (Page) value;
             long total = page.getTotal();
             PageInfoDto pageInfoDto = new PageInfoDto();
             pageInfoDto.setTotal(total);
             PageInfoThreadLocal.set(pageInfoDto);//存入ThreadLocal
         }
         return value;
     }

     @AfterReturning(value = "point()", returning = "a")
     public void afterReturning(Object a) {
         log.debug("正常返回结果:{}", a);
     }

     @AfterThrowing("point()")
     public void afterThrowing() {
         log.debug("目标方法抛出异常");
     }
 }
